package com.changgou.pay.service.impl;

import com.changgou.pay.service.WxPayService;
import com.github.wxpay.sdk.WXPay;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@Service
@Transactional
public class WxPayServiceImpl implements WxPayService {

    @Autowired
    private WXPay wxPay;
    @Value("${wxpay.notify_url}")
    private String notifyUrl;

    @Override
    public Map nativePay(String orderId, Integer money) {

        try {
            Map<String,String> map = new HashMap<>();
            map.put("body","畅购商城");             //商品描述
            map.put("out_trade_no",orderId);    //订单号
            //map.put("total_fee",String.valueOf(money*100));   //金额,以分为单位
            BigDecimal payMoney = new BigDecimal("0.01");
            BigDecimal fen = payMoney.multiply(new BigDecimal("100"));  //1.00
            fen = fen.setScale(0,BigDecimal.ROUND_UP);
            map.put("total_fee",String.valueOf(fen));

            map.put("spbill_create_ip","127.0.0.1");    //终端IP
            map.put("notify_url",notifyUrl);   //回调地址
            map.put("trade_type","NATIVE");     //交易类型
            Map<String, String> mapResult = wxPay.unifiedOrder(map);

            return mapResult;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 查询订单
     * @param orderId
     * @return
     */
    @Override
    public Map queryOrder(String orderId) {
        Map map = new HashMap();
        map.put("out_trade_no",orderId);
        try {
            return wxPay.orderQuery(map);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 关闭订单
     * @param orderId
     * @return
     */
    @Override
    public Map closeOrder(String orderId) {
        Map map = new HashMap();
        map.put("out_trade_no",orderId);

        //调用微信接口关闭订单
        try {
            return  wxPay.closeOrder(map);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
